var appFormly = angular.module('formlyDetail', ['formlyExample']);
app.requires.push('formlyDetail');

appFormly.controller('CustomformDetailCtrl', ['$scope', 'i18nService', '$rootScope', '$parse', '$injector', '$http', '$q', '$state', '$stateParams', '$modal', '$timeout', '$interval', 'SweetAlert', 'FileUploader', 'Restangular', 'BpmRestangular', 'api_configure_form', 'api_bpm_domain', 'api_bpm_data', 'api_user_data',
    function($scope, i18nService, $rootScope, $parse, $injector, $http, $q, $state, $stateParams, $modal, $timeout, $interval, SweetAlert, FileUploader, Restangular, BpmRestangular, api_configure_form, api_bpm_domain, api_bpm_data, api_user_data) {
        //console.log($parse('Restangular')($scope));
        //console.log($injector.get('Restangular'));
        var vm = this;
        vm.options = {
            formState: {
                horizontalLabelClass: 'col-sm-5',
                horizontalFieldClass: 'col-sm-5',
                readOnly: true
            }
        };

        vm.exampleTitle = ['expressionProperties', 'model property'];
        vm.fields = [];
        vm.model = {};
        $scope.langs = i18nService.getAllLangs();
        $scope.lang = 'zh-cn';
        i18nService.setCurrentLang($scope.lang);


        $scope.backFunction = function(data) {
            $state.go('app.incident', {});
        };
        var that = $injector;
        var parse = $parse;

        var formKey = "";
        var pdKey = "";
        if (angular.isDefined($state.current.pdKey) && $state.current.pdKey != "") {
            pdKey = $state.current.pdKey;
            // console.log("pdKey::"+$state.current.pdKey);
        } else if ($stateParams.pdKey) {
            pdKey = $stateParams.pdKey;
        };
        if (angular.isDefined($stateParams.formKey) && $stateParams.formKey != "") {
            formKey = $stateParams.formKey;
            // console.log("formKey::"+$stateParams.formKey);
        }

        //用户测试数据，后续从header的auth中获取
        var userId = 2;

        //==============处理表单设计数据  开始====================
        //处理组件加载后台数据选项的方法
        function refreshSelectOptions(searchVal, field) {
            if (field.templateOptions.optionsUrl) {
                var process = BpmRestangular.all("");
                process.customPOST({ "assignee": 2, "idx": 0, "sum": 1000 }, field.templateOptions.optionsUrl).then(function(result) {
                    if (!field.templateOptions.options) {
                        field.templateOptions.options = [];
                    }
                    if (field.templateOptions.optionsDataKey) {
                        field.templateOptions.options = result[field.templateOptions.optionsDataKey];
                    } else {
                        field.templateOptions.options = result;
                    }
                });
            }
        }
        //解析自定义表单设计数据
        function decodeVMForm(vmForm, mdata) {
            var result = { model: {}, fields: [] };
            //设置模型实体数据 begin
            //        var mdata = vmForm.model;
            //解析数据实体
            //console.log("mdata="+JSON.stringify(mdata));
            var mdata = angular.fromJson(vmForm.model);
            angular.extend(result.model, mdata);

            //设置模型实体数据 end
            //解析设计数据生成表单项 begin
            var fields = [];
            //处理修改设计数据中展示设置
            angular.forEach(vmForm.fields, function(field) {
                if (field.key == "") {
                    delete field.key;
                }

                if (angular.isDefined(field.extjson)) {
                    var extObj = angular.fromJson(field.extjson); //JSON.parse(field.extjson);
                    angular.extend(field.templateOptions, extObj.templateOptions);
                    delete extObj.templateOptions;
                    for (var prop in extObj) {
                        if (new RegExp("Expression").test(prop)) {
                            //var obj = $scope.$eval(extObj[prop]);
                            //extObj[prop] = $scope.$eval(extObj[prop]);
                            if (extObj[prop] != null) {
                                if (new RegExp("function").test(extObj[prop])) {
                                    var propValue = eval(extObj[prop]);
                                    extObj[prop] = propValue;
                                } else {
                                    // console.log(extObj[prop]);
                                    var obj = $scope.$eval(extObj[prop]);
                                    extObj[prop] = obj;
                                    // console.log(obj);
                                }
                            }
                        } else if (new RegExp("expressionProperties").test(prop)) {
                            for (var p in extObj[prop]) {
                                if (new RegExp("function").test(extObj[prop][p])) {
                                    var propValue = eval(extObj[prop][p]);
                                    extObj[prop][p] = propValue;
                                } else {
                                    if (p.indexOf("'") >= 0) {
                                        var obj = $scope.$eval(extObj[prop][p]);
                                        extObj[prop][$scope.$eval(p)] = obj;
                                    }
                                }
                            }
                        } else if ("watcher" == prop) {
                            if (angular.isArray(extObj[prop])) {
                                angular.forEach(extObj[prop], function(item, index) {
                                    for (var p in item) {
                                        if (new RegExp("function").test(item[p])) {
                                            var propValue = eval(item[p]);
                                            extObj[prop][index][p] = propValue;
                                        }
                                    }
                                });
                            } else if (angular.isObject(extObj[prop])) {
                                for (var p in extObj[prop]) {
                                    if (new RegExp("function").test(extObj[prop][p])) {
                                        var propValue = eval(extObj[prop][p]);
                                        extObj[prop][p] = propValue;
                                    }
                                }
                            }
                        }
                    }
                    angular.extend(field, extObj);
                    delete field.extjson;
                }


                if (angular.isDefined(field.templateOptions)) {
                    var templateOs = field.templateOptions;
                    for (var property in templateOs) {
                        // console.log(property);
                        if (angular.isString(templateOs[property]) && (!(new RegExp("[\u4e00-\u9fa5]").test(templateOs[property])) || new RegExp("function").test(templateOs[property]))) {
                            if (new RegExp("function").test(templateOs[property])) {
                                var propValue = eval(templateOs[property]);
                                field.templateOptions[property] = propValue;
                            } else {
                                if (that.has(templateOs[property])) {
                                    field.templateOptions[property] = that.get(templateOs[property]);
                                } else {
                                    field.templateOptions[property] = templateOs[property];
                                }
                            }
                        } else if (templateOs[property] == null) {
                            //delete field.templateOptions[property];
                        } else {

                        }
                    }
                }
                // console.log(field);
                if (angular.isDefined(field.templateOptions) && angular.isDefined(field.templateOptions.extjson)) {
                    var extObj = angular.fromJson(field.templateOptions.extjson); //JSON.parse(field.extjson);
                    angular.extend(field.templateOptions, extObj);
                    delete field.templateOptions.extjson;
                }
                //...
                if (field.templateOptions) {
                    //处理远程获取数据控件方法调用
                    if (field.templateOptions.optionsUrl) {
                        field.templateOptions.refresh = refreshSelectOptions;
                    }


                    //处理嵌套属性数据绑定/
                    if (field.templateOptions.pkey) {
                        var pmodel, i = 0;
                        angular.forEach(field.templateOptions.pkey.split("."), function(p) {
                            if (i == 0) {
                                if (result.model[p] == null) {
                                    result.model[p] = {};
                                }
                                pmodel = result.model[p];
                                i++;
                            } else {
                                if (pmodel[p] == null) {
                                    pmodel[p] = {};
                                }
                                pmodel = pmodel[p];
                            }
                        });
                        if (pmodel != null) {
                            field.model = pmodel;
                            if (pmodel[field.key] == null) {
                                pmodel[field.key] = null;
                            }
                        }
                    } else {
                        if (result.model[field.key] == null) {
                            result.model[field.key] = null;
                        }
                    }
                    //处理弹出框组件初始化
                    if (field.type == "ui-input-selectmodal") {
                        field.templateOptions.modal = $modal;
                        //field.templateOptions.Restangular = Restangular;
                    } else if (field.type == "ui-userselect") {
                        field.templateOptions.modal = $modal;
                        //field.templateOptions.Restangular = Restangular;
                    } else if (field.type == "ui-multiuserselect") {
                        field.templateOptions.modal = $modal;
                    } else if (field.type == "ui-modelselect") {
                        field.templateOptions.modal = $modal;
                        //field.templateOptions.Restangular = Restangular;
                    } else if (field.type == "ui-dropfile") {
                        field.templateOptions.fileUploader = new FileUploader({
                            url: '/uploader'
                        });
                        field.templateOptions.taskId = $stateParams.taskId;
                        field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                        field.templateOptions.userId = $rootScope.user.id;
                        //field.ApiService=api_bpm_domain;
                    } else if (field.type == "ui-dropfiletable") {
                        field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                    }
                }

                //          console.log(field);
                result.fields.push(field);
            });
            angular.extend($scope.vm.fields, result.fields);
            angular.extend($scope.vm.model, result.model);
            $scope.formData = vmForm;
            //console.log($scope.vm);

            //解析设计数据生成表单项 end
            return result;
        }
        //======================处理表单设计数据  结束========================
        $scope.closeModel = function() {
            console.log("pdKey=" + pdKey);
            // if ($stateParams.pdKey) {
            //     pdKey = $stateParams.pdKey;
            // }
            if (pdKey == "incident") {
                $state.go('app.incident.list', {});
            } else if (pdKey == "change") {
                $state.go('app.change.list', {});
            } else if (pdKey == "problem") {
                $state.go('app.problem.list', {});
            } else if (pdKey == "release") {
                $state.go('app.release.list', {});
            } else if (pdKey == "schedule") {
                $state.go('app.scheduling.list', {});
            } else if (pdKey == "configure") {
                $state.go('app.cmdb.plist', {});
            } else if (pdKey == "serviceCatalogueProcessActual") {
                $state.go('app.reService.manager', {});
            } else if (pdKey == "inspectionListForm") {
                $state.go('app.inspection.inspectList', {});
            } else if (pdKey == "bpm_inspection") {
                $state.go('app.inspection.inspectList', {});
            } else if (pdKey == "bpm_service_request") {
                $state.go('app.reService.manager', {});
            };
            event.preventDefault();
        };
        vm.submit = function(data, style) {

        };

        $scope.vm = vm;

        var dataId = $stateParams.dataId;
        var pdKey = $stateParams.pdKey;
        var detailFormKey = $stateParams.formKey;
        var processInstanceId = $stateParams.processInstanceId;
        if (angular.isDefined(detailFormKey) && detailFormKey != "") {
            var dataId = parseInt(dataId);
            if (angular.isDefined(processInstanceId) && processInstanceId != "") {
                api_configure_form.renderForm(detailFormKey, '00000', processInstanceId).then(function(responseData) {
                    if (responseData) {
                        var vmForm = Restangular.stripRestangular(responseData);
                        if (vmForm) {
                            var modelData = {};
                            modelData[pdKey] = vmForm.model;
                            decodeVMForm(vmForm, modelData);
                        }
                    }
                });

            } else if (angular.isDefined(dataId) && dataId != "") {
                api_bpm_data.fetchData(pdKey, dataId).then(function(response) {
                    if (response) {
                        var myData = Restangular.stripRestangular(response);
                        var processInstanceId = myData.data.processInstanceId;
                        //$scope.vm.model[pdKey]=myData.data;
                        api_configure_form.renderForm(detailFormKey, '00000', processInstanceId).then(function(responseData) {
                            if (responseData) {
                                // console.log("responseData>>>");console.log(responseData);
                                var vmForm = Restangular.stripRestangular(responseData);
                                if (vmForm) {
                                    //console.log("vmForm>>>");console.log(vmForm);
                                    var modelData = {};
                                    modelData[pdKey] = vmForm.model;
                                    decodeVMForm(vmForm, modelData);
                                }
                            }

                        });
                    }
                })
            }

        } else {
            // create process instance
            if (pdKey != "") { //for process
                api_bpm_domain.startformkey(pdKey).then(function(response) {
                    if (response) {
                        var myData = Restangular.stripRestangular(response);
                        api_configure_form.renderForm(myData.data).then(function(responseData) {
                            if (responseData) {
                                var vmForm = Restangular.stripRestangular(responseData);
                                if (vmForm) {
                                    decodeVMForm(vmForm);
                                    console.log($scope);
                                }
                            }
                        });
                    }
                });
            } else { //for form
                //TODO
                //测试数据 开始
                var testJson = {
                    fields: [{
                            key: 'formtitle',
                            type: 'ui-title',
                            noFormControl: true,
                            templateOptions: {
                                label: 'title is ',
                                placeholder: 'Formly is terrific!'
                            }
                        },
                        {
                            key: 'a',
                            type: 'ui-input',
                            className: 'col-xs-4',
                            templateOptions: {
                                type: 'input',
                                label: 'input a',
                                placeholder: 'search a...',
                                lBtn: {
                                    label: 'input',
                                    onClick: function(val, opt, el, ev, model) { alert(val); }
                                },
                                rAddon: '@111.cc'
                            }
                        },
                        {
                            key: 'b',
                            type: 'ui-input',
                            className: 'col-xs-4',
                            templateOptions: {
                                type: 'input',
                                label: 'input a',
                                placeholder: 'search a...',
                                rBtn: {
                                    icon: 'glyphicon-search',
                                    onClick: function(val, opt, el, ev, model) { alert(val); }
                                },
                                lAddon: '@'
                            }
                        },
                        {
                            key: 'first',
                            type: 'ui-input',
                            className: 'col-xs-2',
                            templateOptions: {
                                type: 'input',
                                label: 'first name',
                                pkey: 'name'
                            }
                        },
                        {
                            key: 'last',
                            type: 'ui-input',
                            className: 'col-xs-2',
                            templateOptions: { type: 'input', label: 'last name', pkey: 'name' }
                        },
                        {
                            key: 'username',
                            type: 'ui-input',
                            className: 'col-xs-6',
                            templateOptions: {
                                type: 'input',
                                label: 'User Name',
                                placeholder: 'Enter name',
                                required: true,
                                maxLength: 10
                            }
                        },
                        {
                            key: 'password',
                            type: 'ui-input',
                            className: 'col-xs-6',
                            templateOptions: {
                                type: 'password',
                                label: 'Password',
                                placeholder: 'Password',
                                required: true
                            },
                            expressionProperties: {
                                'templateOptions.disabled': '!model.username'
                            }
                        },
                        {
                            key: 'selectmodal',
                            type: 'ui-input-selectmodal',
                            className: 'col-xs-6',
                            templateOptions: {
                                label: 'selectmodal',
                                btnLabel: 'search',
                                btnClassName: 'btn-o',
                                modalParam: {
                                    items: function() {
                                        return ['a', 'b', 'c', 'd'];
                                    },
                                    title: function() {
                                        return '测试标题';
                                    }
                                }
                            }
                        },
                        {
                            key: 'email',
                            type: 'ui-input',
                            className: 'col-xs-6',
                            templateOptions: {
                                type: 'email',
                                maxlength: 10,
                                minlength: 6,
                                label: 'EMail'
                            }
                        },
                        {
                            key: 'date',
                            type: 'ui-datepicker',
                            className: 'col-xs-6',
                            templateOptions: {
                                label: 'Date',
                                type: 'text',
                                datepickerPopup: 'yyyy-MM-dd hh:mm:ss',
                                initDate: function() {
                                    return new Date();
                                }

                            }
                        },
                        {
                            key: 'multiselectItem',
                            type: 'ui-multi-select-tree',
                            className: 'col-xs-6',
                            templateOptions: {
                                label: 'multiSelect',
                                placeholder: '请选择...',
                                isMultiSelect: false,
                                selLeafs: false, //只选叶子节点
                                refreshData: function(APIService) {
                                    return APIService.fetchDataList('changeclassify', { 'idx': 0, 'sum': 100 });
                                },
                                APIService: api_bpm_data,
                                optionsDataKey: 'list',
                                refreshDelay: 1000,
                                onDataCallback: function(item, selectItems, options, field, model) {
                                    model[options.key] = { id: item.id };
                                }
                            }
                        },
                        {
                            key: 'selectItem',
                            type: 'ui-select',
                            className: 'col-xs-4',
                            templateOptions: {
                                label: 'ui-select',
                                valueProp: 'code', //对应value
                                labelProp: 'source', //对应key
                                optionsUrl: 'data/fetchDataList/incidentsource', //对应后台地址，api/之前的部分省略
                                optionsDataKey: 'list', //对应返回数组数据的键值,
                                required: true,
                                onChange: function(val, options, field, event, model) {
                                    model.start_code = val;
                                }
                            }
                        },
                        {
                            key: 'multiselectItem',
                            type: 'ui-multiselect',
                            className: 'col-xs-4',
                            templateOptions: {
                                label: 'multi-select',
                                valueProp: 'code', //对应value
                                labelProp: 'source', //对应key
                                optionsUrl: 'data/fetchDataList/incidentsource', //对应后台地址，api/之前的部分省略
                                optionsDataKey: 'list', //对应返回数组数据的键值,
                                required: true,
                                onChange: function(val, options, field, event, model) {
                                    console.log(val);
                                    console.log(model);
                                    //model.start_code = val;
                                }
                            }
                        },
                        {
                            key: 'checklistItem',
                            type: 'ui-checklist',
                            className: 'col-xs-4',
                            templateOptions: {
                                label: 'checklistItem',
                                options: [
                                    { name: 'Iron Man', value: 'iron_man' },
                                    { name: 'Captain America', value: 'captain_america' },
                                    { name: 'Black Widow', value: 'black_widow' },
                                    { name: 'Hulk', value: 'hulk' },
                                    { name: 'Captain Marvel', value: 'captain_marvel' }
                                ]
                            }
                        },
                        {
                            key: 'radioItem',
                            type: 'ui-radio',
                            className: 'col-xs-4',
                            templateOptions: {
                                label: 'radioItem',
                                options: [
                                    { name: 'Iron Man', value: 'iron_man' },
                                    { name: 'Captain America', value: 'captain_america' },
                                    { name: 'Black Widow', value: 'black_widow' },
                                    { name: 'Hulk', value: 'hulk' },
                                    { name: 'Captain Marvel', value: 'captain_marvel' }
                                ],
                                type: 'number'
                            }
                        },
                        {
                            key: 'selectUser',
                            type: 'ui-userselect',
                            className: 'col-xs-12',
                            templateOptions: {
                                label: '请求人信息',
                                modalTitle: '请求人列表',
                                fetchItems: function(filterData, APIService) {
                                    return APIService.fetchDataList('user', filterData);
                                },
                                Restangular: Restangular,
                                ApiService: api_user_data,
                                onClick: function(val, options, field, event, model) {
                                    //model.start_code++;
                                    console.log(options);
                                }
                            }
                        },
                        {
                            key: 'cabUser',
                            type: 'ui-multiuserselect',
                            className: 'col-xs-12',
                            templateOptions: {
                                label: 'CAB评审成员',
                                modalTitle: 'CAB成员列表',
                                fetchItems: function(filterData, APIService) {
                                    return APIService.fetchDataList('user', filterData);
                                },
                                Restangular: Restangular,
                                ApiService: api_user_data,
                                onClick: function(val, options, field, event, model) {
                                    console.log(model);
                                }
                            }
                        },
                        {
                            key: 'incident',
                            type: 'ui-modelselect',
                            className: 'col-xs-3',
                            templateOptions: {
                                label: '关联事件工单',
                                modalTitle: '事件列表',
                                fetchItems: function(filterData, APIService) {
                                    return APIService.fetchDataList('incident', filterData);
                                },
                                Restangular: "Restangular",
                                ApiService: "api_bpm_data",
                                columnDefs: [
                                    { name: 'id', width: 80, enableFiltering: false },
                                    { name: 'title', displayName: '事件主题', width: 140 },
                                    { name: 'type.name', displayName: '事件类型', width: 140 },
                                    { name: 'emergency.name', displayName: '紧急度', width: 80 },
                                    { name: 'state.name', displayName: '状态', width: 100 },
                                    { name: 'emergency.name', displayName: '紧急度', width: 80 },
                                    { name: 'influence.name', displayName: '影响度', width: 80 },
                                    { name: 'priority.name', displayName: '优先级', width: 80 },
                                    { name: 'handlerUser.name', displayName: '当前处理人', width: 100 },
                                    { name: 'acceptDate', displayName: '创建时间', width: 100 }
                                ],
                                displayName: 'title',
                                onClick: function(val, options, field, event, model) {
                                    //model.start_code++;
                                    console.log(options);
                                }
                            }
                        },
                        {
                            key: 'worknumber',
                            type: 'ui-workernumber',
                            className: 'col-xs-3',
                            templateOptions: {
                                label: 'work number',
                                Restangular: Restangular,
                                ApiService: api_bpm_domain,
                                getWorkernumber: function(APIService) {
                                    return APIService.workernumber('bg');
                                }
                            }
                        },
                        {
                            key: 'chkme',
                            type: 'ui-checkbox',
                            className: 'col-xs-3',
                            templateOptions: {
                                label: 'Check me out'
                            }
                        },
                        {
                            key: 'droplink',
                            type: 'ui-link',
                            className: 'col-xs-3',
                            templateOptions: {
                                label: '添加附件',
                                onClick: function(val, options, field, event, model) {
                                    if (angular.isUndefined(field.form.dropState)) {
                                        field.form.dropState = false;
                                    }
                                    field.form.dropState = !field.form.dropState;
                                    console.log(field);
                                }
                            }
                        },
                        {
                            key: 'dropfile',
                            type: 'ui-dropfile',
                            className: 'col-xs-12',
                            templateOptions: {
                                label: '附件',
                                uploadUrl: 'http://127.0.0.1:9008/saveAttachments'
                            }
                        },
                        {
                            key: 'droplist',
                            type: 'ui-dropfiletable',
                            className: 'col-xs-12',
                            templateOptions: {
                                label: '附件下载列表',
                                Restangular: Restangular,
                                ApiService: api_bpm_domain
                            }

                        },
                        {
                            key: 'start_code',
                            className: 'col-xs-6',
                            type: 'ui-hidden'
                        },
                        {
                            key: 'remark',
                            type: 'ui-textarea',
                            className: 'col-xs-12',
                            templateOptions: {
                                label: 'remark is ',
                                rows: 3
                            }
                        },
                        {
                            key: 'setStartCode',
                            type: 'ui-button',
                            className: 'col-xs-4',
                            templateOptions: {
                                label: 'customButton',
                                onClick: function(val, options, field, event, model) {
                                    model.start_code++;
                                    console.log(options);
                                }
                            }
                        }
                    ],
                    model: {
                        username: "robin lau",
                        password: "123456",
                        chkme: false,
                        start_code: 0,
                        formtitle: "Hey!I am title value!",
                        name: {
                            first: "robin",
                            last: "lau"
                        },
                        multiselectItem: []
                            //date:"2015-09-15 00:00:00"
                    }
                };
                setTimeout(function() {
                    decodeVMForm(testJson);
                    $scope.$apply();
                }, 500);
                //测试数据结束
            }
        }
    }
]);